package com.deuwise.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.deuwise.common.utils.MapUtils;
import com.deuwise.system.entity.SysUserRole;
import com.deuwise.system.service.SysUserRoleService;
import com.deuwise.system.mapper.SysUserRoleMapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  接口实现类
 *@author deuwise
 *@date 2018-11-06 14:15:04
 **/
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    Logger logger= LoggerFactory.getLogger(SysUserRoleServiceImpl.class);

    @Override
    public List<String> queryRoleIdList(String userId) {
        Wrapper<SysUserRole> wrapper=new EntityWrapper<>();
        wrapper.eq("user_id",userId);
        List<SysUserRole> userRoleList= this.selectList(wrapper);
        if(userRoleList!=null&&userRoleList.size()>0){
            return  userRoleList.stream().map(f->{
                return  f.getRoleId();
            }).collect(Collectors.toList());
        }
        return  null;
    }

    @Override
    public void saveOrUpdate(String userId, List<String> roleIdList) {
        //先删除用户与角色关系
        this.deleteByMap(new MapUtils().put("user_id", userId));

        if(roleIdList == null || roleIdList.size() == 0){
            return ;
        }

        //保存用户与角色关系
        List<SysUserRole> list = new ArrayList<>(roleIdList.size());
        for(String roleId : roleIdList){
            SysUserRole sysUserRoleEntity = new SysUserRole();
            sysUserRoleEntity.setUserId(userId);
            sysUserRoleEntity.setRoleId(roleId);

            list.add(sysUserRoleEntity);
        }
        this.insertBatch(list);
    }
}